<template>
    <div v-loading="bottomLoading">
        <div class="tabs">
            <span 
                class="tab-item"
                v-for="(item, index) in tabs"
                :key="index"
                :class="{active:item.key == curTab}"
                @click="changeTab(item)"
            >
                {{item.name}}
            </span>
        </div>
        <DiscussList
            :data="data.list"
            :has-more="data.hasMore"
            @update:list="refresh"
            :is-creater="isCreater"
            :is-buy-person="isBuyPerson"
            :is-preview="isPreview"/>
    </div>
</template>

<script setup>
import addDiscuss from './discuss/add.vue';
import DiscussList from './discuss/index.vue';
import { ref, reactive, onBeforeUnmount, nextTick } from 'vue';
import { Throttle, queryToJson } from '@/lib/tools';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';

const route = useRoute();

const store = useStore();

defineExpose({
    refresh
})

const props = defineProps({
    detail: {
        type: Object,
        default: () => {}
    },
    isCreater: { // 是否是创建者
        type: Boolean,
        default: false
    },
    isBuyPerson: { // 是否是购买者
        type: Boolean,
        default: false
    },
    isPreview: { // 是否是预览状态
        type: Boolean,
        default: false
    }
})

// 底部加载
const bottomLoading = ref(false);

const curTab = ref(0)

const tabs = ref([
    {name: '全部', key: 0},
    {name: '我的', key: 1}
])

const data = reactive({
    list: [],
    hasMore: true
})

const pageIndex = ref(1);

function changeTab(item){
    curTab.value = item.key
    pageIndex.value = 1;
    data.list = [];
    data.hasMore = true;
    getCommentList()
}

// 获取评论列表
function getCommentList () {
    let catalogueId = queryToJson().catalogueId;
    if (!route.params?.moocId || !catalogueId || !data.hasMore) {
        return false;
    }
    bottomLoading.value = true;
    
    G_transmit('commentListByCatalogue', {
        queries: {
            bizId: catalogueId, // 课件id
            bizSource: 'mooc', // 主体来源
            commentLevel: 1, // 层级(1:一级评论, 2:二级评论 n:n级评论）
            pageIndex: pageIndex.value, // 第几页
            pageSize: 20, // 页面大小 （只有在pageSize=20 的条件下才能使用缓存）
            parentSource: route.params.moocId, // 慕课id
            parentCommentId: 0, // # 父级评论ID 一级评论传0
            topParentCommentId: 0,
            operationBizSource: 'moocComment',
            myComment: curTab.value
        }
    }).then((res) => {
        res.data.rows = res.data.rows && res.data.rows.map(item => {
            return {
                ...item,
                showReplyInput: false,
                showReply: false,
                hasMoreReply: true,
            }
        }) || []
		if (data.list.length <= res?.data?.total) {
			data.list = [...data.list, ...(res?.data?.rows || [])];
		}
        if (data.list.length >= res?.data?.total) {
			data.hasMore = false;
		}
    }).finally(() => {
        bottomLoading.value = false;
    })
}

// 更新评论后到第一页
function refresh () {
    window.removeEventListener('scroll', handleScroll);
    pageIndex.value = 1;
    data.list = [];
    data.hasMore = true;
    // document.body.scrollIntoView({
    //     behavior: 'smooth',
    //     block: 'start'
    // });
    getCommentList();
    nextTick(() => {
		window.addEventListener('scroll', handleScroll, true)
	})
}

// 划到底部加载动态
const handleScroll = Throttle(function (e) {
	let scrollTop =
		document.documentElement.scrollTop || document.body.scrollTop
	let clientHeight = document.documentElement.clientHeight
	let scrollHeight = document.documentElement.scrollHeight
    // console.log(scrollTop, clientHeight, scrollHeight, scrollTop + clientHeight >= scrollHeight - 500, scrollTop + clientHeight, scrollHeight - 500);
	if (scrollTop + clientHeight >= scrollHeight - 500 && data.hasMore) {
		pageIndex.value++;
        // console.log(pageIndex.value, 'Throttle');
		getCommentList();
	}
}, 800)

onBeforeUnmount(() => {
	window.removeEventListener('scroll', handleScroll);
})
</script>

<style lang="scss" scoped>
.divider-wrap {
    border-top: 1px solid #EFF0F2;
    margin: 20px 0 10px;
}
.tabs{
    font-size: 14px;
    color: #222222;
    display: flex;
    align-items: center;
    .tab-item{
        width:52px;
        height:32px;
        text-align: center;
        line-height: 32px;
        margin-right: 8px;
        cursor: pointer;
    }
    .active{
        background: #E7F1FF;
        border-radius: 16px;
        color: #0084F6;
    }
}
</style>